package common

import (
	"encoding/json"
	"errors"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"my-desktop/config"
	"my-desktop/models"
	"net/http"
	"net/url"
	"strings"
)

// 请求体中获取数据
func GetRequestJsonParam(r *http.Request) map[string]interface{} {
	var params map[string]interface{}
	body, _ := ioutil.ReadAll(r.Body)
	_ = json.Unmarshal(body, &params)
	return params
}

// 请求体中获取Cookie
func GetToken(r *http.Request, headerName string) (string, error) {
	header := r.Header
	token := header.Get(headerName)
	if len(token) == 0 {
		return "", errors.New("没有权限")
	}
	return strings.TrimPrefix(token, config.Http.TokenPrefix+" "), nil
}

func Error(w http.ResponseWriter, code int, message string, err error) {
	var result models.Result
	result.Code = code
	result.Message = message
	result.Data = err.Error()
	resultJson, _ := json.Marshal(result)
	w.Header().Set("Content-Type", "application/json")
	_, err = w.Write(resultJson)
	if err != nil {
		logrus.Error(err)
	}
}

func Success(w http.ResponseWriter, code int, message string, data interface{}) {
	var result models.Result
	result.Code = code
	result.Message = message
	result.Data = data
	resultJson, _ := json.Marshal(result)
	w.Header().Set("Content-Type", "application/json")
	_, err := w.Write(resultJson)
	if err != nil {
		logrus.Error(err)
	}
}

// 客户端发送过来的数据是 url 编码过的，这里需要解码
func UrlQueryUnescape(old string) (string, error) {
	// url.QueryUnescape 会将'+'加号转换为' '空格。
	// 必须先替换 % ，再替换 +
	return url.QueryUnescape(strings.ReplaceAll(strings.ReplaceAll(old, "%", "%25"), "+", "%2b"))
}
